define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        // 应付账款列表
        payable: function () {
            Table.api.init({
                extend: {
                    index_url: 'scanwork/supplier_payment/payable' + location.search,
                    add_url: 'scanwork/supplier_payment/createPayable',
                    edit_url: 'scanwork/supplier_payment/edit',
                    del_url: 'scanwork/supplier_payment/del',
                    multi_url: 'scanwork/supplier_payment/multi',
                    table: 'scanwork_supplier_payable',
                }
            });

            var table = $("#table");

            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'payable_no', title: '应付账款编号', operate: 'LIKE'},
                        {field: 'supplier_name', title: '供应商', operate: 'LIKE'},
                        {field: 'inbound_no', title: '入库单号', operate: 'LIKE'},
                        {field: 'total_amount', title: '应付总金额', operate:'BETWEEN', sortable: true, formatter: function(value, row, index) {
                            return '¥' + parseFloat(value || 0).toFixed(2);
                        }},
                        {field: 'paid_amount', title: '已付金额', operate:'BETWEEN', sortable: true, formatter: function(value, row, index) {
                            return '¥' + parseFloat(value || 0).toFixed(2);
                        }},
                        {field: 'remaining_amount', title: '剩余应付', operate:'BETWEEN', sortable: true, formatter: function(value, row, index) {
                            return '¥' + parseFloat(value || 0).toFixed(2);
                        }},
                        {field: 'due_date', title: '到期日期', operate:'BETWEEN', sortable: true, addclass: 'datetimerange', formatter: Table.api.formatter.date},
                        {field: 'status', title: '状态', searchList: {'pending':'待付款','partial':'部分付款','paid':'已付清','overdue':'逾期'}, formatter: function(value, row, index) {
                            var statusMap = {
                                'pending': {text: '待付款', class: 'warning'},
                                'partial': {text: '部分付款', class: 'info'},
                                'paid': {text: '已付清', class: 'success'},
                                'overdue': {text: '逾期', class: 'danger'}
                            };
                            var status = statusMap[value] || {text: '未知', class: 'default'};
                            return '<span class="label label-' + status.class + '">' + status.text + '</span>';
                        }},
                        {field: 'createtime', title: '创建时间', operate:'BETWEEN', sortable: true, addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            Table.api.bindevent(table);
            
            // 从入库单创建应付账款按钮事件
            $(document).on('click', '.btn-create-from-inbound', function() {
                Fast.api.open('scanwork/supplier_payment/createPayableFromInbound', '从入库单创建应付账款', {
                    callback: function(data) {
                        table.bootstrapTable('refresh');
                    }
                });
            });
        },

        // 付款记录列表
        payment: function () {
            Table.api.init({
                extend: {
                    index_url: 'scanwork/supplier_payment/payment' + location.search,
                    add_url: 'scanwork/supplier_payment/createPayment',
                    edit_url: 'scanwork/supplier_payment/edit',
                    del_url: 'scanwork/supplier_payment/del',
                    multi_url: 'scanwork/supplier_payment/multi',
                    table: 'scanwork_supplier_payment',
                }
            });

            var table = $("#table");

            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'payment_no', title: '付款单号', operate: 'LIKE'},
                        {field: 'supplier_name', title: '供应商', operate: 'LIKE'},
                        {field: 'payable_no', title: '应付账款编号', operate: 'LIKE'},
                        {field: 'payment_amount', title: '付款金额', operate:'BETWEEN', sortable: true, formatter: function(value, row, index) {
                            return '¥' + parseFloat(value || 0).toFixed(2);
                        }},
                        {field: 'payment_date', title: '付款日期', operate:'BETWEEN', sortable: true, addclass: 'datetimerange', formatter: Table.api.formatter.date},
                        {field: 'payment_method', title: '付款方式', searchList: {'cash':'现金','bank_transfer':'银行转账','check':'支票','other':'其他'}, formatter: function(value, row, index) {
                            var methodMap = {
                                'cash': '现金',
                                'bank_transfer': '银行转账',
                                'check': '支票',
                                'other': '其他'
                            };
                            return methodMap[value] || value;
                        }},
                        {field: 'reference_no', title: '参考号', operate: 'LIKE'},
                        {field: 'status', title: '状态', searchList: {'pending':'待确认','confirmed':'已确认','cancelled':'已取消'}, formatter: function(value, row, index) {
                            var statusMap = {
                                'pending': {text: '待确认', class: 'warning'},
                                'confirmed': {text: '已确认', class: 'success'},
                                'cancelled': {text: '已取消', class: 'danger'}
                            };
                            var status = statusMap[value] || {text: '未知', class: 'default'};
                            return '<span class="label label-' + status.class + '">' + status.text + '</span>';
                        }},
                        {field: 'createtime', title: '创建时间', operate:'BETWEEN', sortable: true, addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            Table.api.bindevent(table);
        },

        // 发票管理列表
        invoice: function () {
            Table.api.init({
                extend: {
                    index_url: 'scanwork/supplier_payment/invoice' + location.search,
                    add_url: 'scanwork/supplier_payment/add',
                    edit_url: 'scanwork/supplier_payment/edit',
                    del_url: 'scanwork/supplier_payment/del',
                    multi_url: 'scanwork/supplier_payment/multi',
                    table: 'scanwork_supplier_invoice',
                }
            });

            var table = $("#table");

            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'invoice_no', title: '发票号', operate: 'LIKE'},
                        {field: 'supplier_name', title: '供应商', operate: 'LIKE'},
                        {field: 'inbound_no', title: '入库单号', operate: 'LIKE'},
                        {field: 'invoice_date', title: '开票日期', operate:'BETWEEN', sortable: true, addclass: 'datetimerange', formatter: Table.api.formatter.date},
                        {field: 'invoice_amount', title: '发票金额', operate:'BETWEEN', sortable: true, formatter: function(value, row, index) {
                            return '¥' + parseFloat(value || 0).toFixed(2);
                        }},
                        {field: 'tax_amount', title: '税额', operate:'BETWEEN', sortable: true, formatter: function(value, row, index) {
                            return '¥' + parseFloat(value || 0).toFixed(2);
                        }},
                        {field: 'total_amount', title: '发票总金额', operate:'BETWEEN', sortable: true, formatter: function(value, row, index) {
                            return '¥' + parseFloat(value || 0).toFixed(2);
                        }},
                        {field: 'invoice_type', title: '发票类型', searchList: {'vat':'增值税发票','normal':'普通发票','receipt':'收据'}, formatter: function(value, row, index) {
                            var typeMap = {
                                'vat': '增值税发票',
                                'normal': '普通发票',
                                'receipt': '收据'
                            };
                            return typeMap[value] || value;
                        }},
                        {field: 'status', title: '状态', searchList: {'pending':'待审核','verified':'已审核','rejected':'已拒绝'}, formatter: function(value, row, index) {
                            var statusMap = {
                                'pending': {text: '待审核', class: 'warning'},
                                'verified': {text: '已审核', class: 'success'},
                                'rejected': {text: '已拒绝', class: 'danger'}
                            };
                            var status = statusMap[value] || {text: '未知', class: 'default'};
                            return '<span class="label label-' + status.class + '">' + status.text + '</span>';
                        }},
                        {field: 'createtime', title: '创建时间', operate:'BETWEEN', sortable: true, addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            Table.api.bindevent(table);
        },

        // 创建应付账款
        createPayable: function () {
            Controller.api.bindevent();
        },

        // 创建付款记录
        createPayment: function () {
            Controller.api.bindevent();
        },

        // 从入库单创建应付账款
        createPayableFromInbound: function () {
            Controller.api.bindevent();
            
            // 全选/取消全选
            $('#select-all').on('change', function() {
                $('.inbound-checkbox').prop('checked', $(this).prop('checked'));
            });
            
            // 单个选择时更新全选状态
            $('.inbound-checkbox').on('change', function() {
                var totalCheckboxes = $('.inbound-checkbox').length;
                var checkedCheckboxes = $('.inbound-checkbox:checked').length;
                $('#select-all').prop('checked', totalCheckboxes === checkedCheckboxes);
            });
            
            // 表单提交
            $('#create-payable-form').on('submit', function(e) {
                e.preventDefault();
                
                var selectedIds = [];
                $('.inbound-checkbox:checked').each(function() {
                    selectedIds.push($(this).val());
                });
                
                if (selectedIds.length === 0) {
                    Toastr.warning('请选择要创建应付账款的入库单');
                    return;
                }
                
                Layer.confirm('确定要为选中的入库单创建应付账款吗？', function(index) {
                    $.ajax({
                        url: 'scanwork/supplier_payment/createPayableFromInbound',
                        type: 'POST',
                        data: {inbound_ids: selectedIds},
                        dataType: 'json',
                        success: function(data) {
                            Layer.close(index);
                            if (data.code == 1) {
                                Toastr.success(data.msg || '应付账款创建成功');
                                setTimeout(function() {
                                    location.reload();
                                }, 1500);
                            } else {
                                Toastr.error(data.msg || '创建失败');
                            }
                        },
                        error: function(xhr, status, error) {
                            Layer.close(index);
                            Toastr.error('创建失败：' + error);
                        }
                    });
                });
            });
        },

        // 供应商对账
        reconciliation: function () {
            Controller.api.bindevent();
            
            // 自动计算差异金额
            $('input[name="row[our_amount]"], input[name="row[supplier_amount]"]').on('input', function() {
                var ourAmount = parseFloat($('input[name="row[our_amount]"]').val()) || 0;
                var supplierAmount = parseFloat($('input[name="row[supplier_amount]"]').val()) || 0;
                var difference = ourAmount - supplierAmount;
                $('input[name="row[difference_amount]"]').val(difference.toFixed(2));
            });
        },

        // 获取供应商应付账款统计
        getSupplierPayableStats: function () {
            var supplierId = $('#supplier-select').val();
            
            Fast.api.ajax({
                url: 'scanwork/supplier_payment/getSupplierPayableStats',
                data: {supplier_id: supplierId},
                success: function(data, ret) {
                    if (data.code == 1) {
                        // 更新统计信息显示
                        updateStatsDisplay(data.data);
                    }
                }
            });
        },

        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };

    // 更新统计信息显示
    function updateStatsDisplay(stats) {
        $('#total-count').text(stats.total_count || 0);
        $('#total-amount').text('¥' + parseFloat(stats.total_amount || 0).toFixed(2));
        $('#paid-amount').text('¥' + parseFloat(stats.paid_amount || 0).toFixed(2));
        $('#remaining-amount').text('¥' + parseFloat(stats.remaining_amount || 0).toFixed(2));
        $('#pending-count').text(stats.pending_count || 0);
        $('#partial-count').text(stats.partial_count || 0);
        $('#paid-count').text(stats.paid_count || 0);
        $('#overdue-count').text(stats.overdue_count || 0);
    }

    return Controller;
});
